package com.gdit.zax.utils;

import java.util.Date;


public class VeriFicUtil {
	private static DES des;
	static {
		try {
			des = new DES("touch_ping");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取id的验证密文
	 * @param id
	 * @return
	 */
	public static String getIDVF(int id) {
		String key = null;
		try {
			if (des==null) des = new DES("touch_ping");
			String str = id + "," + System.currentTimeMillis();
			String str2 = TextUtil.reverse(str);
			key = des.encrypt(str2);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return key;
	}
	
	/**
	 * 获取id验证，失败则返回int最小值(30天超时)
	 * @param id
	 * @return intmax>>key超时 intmin>>错误的token
	 */
	public static int getVFID(String key) {
		return getVFID(key, 1000 * 60 * 60 * 24 * (long)30);//30天超时
	}
	
	public static int getVFID(String key,long timeout) {
		try {
			if (des==null) des = new DES("touch_ping");
			String vkey = des.decrypt(key);
			String str = TextUtil.reverse(vkey);
			String[] str0 = str.split(",");
			if (str0.length==2) {
				long oldtime = Long.parseLong(str0[1]);
				int id = Integer.parseInt(str0[0]);
				if (System.currentTimeMillis() - oldtime < timeout) {
					return id;
				} else {
					//token过期
					System.out.println("id已过时:" + id + " time:" + new Date(oldtime).toLocaleString());
					return Integer.MAX_VALUE;
				}
			} else {
				System.out.println("key格式不符合");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		//key格式不对!!
		return Integer.MIN_VALUE;
	}
	
	
	/**
	 * 获取验证的key
	 * @param filename文件名
	 * @param key (1天过时)
	 * @return
	 */
	public static boolean isVerification(String filename,String key) {
		try {
			String mingwen = des.decrypt(key);//最初明文
			String mingwen_l = mingwen.substring(0, 4);//filename的MD5的前4位
			String mingwen_r = mingwen.substring(4, mingwen.length());//混序的时间
			
			
			if (mingwen_l.equals(MD5.getMD5(filename).substring(0, 4))) {
				mingwen_r = TextUtil.reverse(mingwen_r);//正确顺序的时间
				
				long oldtime = Long.parseLong(mingwen_r);
				long nowtime = System.currentTimeMillis();
				if (nowtime-oldtime <= 1000*60*60*24*1) {//生成的连接1天过时
					return true;
				} else {
//					System.out.println("key超时");
				}
			} else {
//				System.out.println("文件名md5不同");
			}
		} catch (Exception e) {
//			System.out.println("des解密失败");
			e.printStackTrace();
		}
		return false;
	}
	
	
//	/**
//	 * 获取视频验证key
//	 * @param filename文件名
//	 * @return
//	 */
//	public static String getVerification(String filename) {
//		try {
//			String str1 = System.currentTimeMillis()+"";//时间，毫秒
//			String str2= TextUtil.reverse(str1);//混序的时间
//			String str3 = MD5.getMD5(filename).substring(0, 4) +  str2;//filename的MD5的前4位
//			String key = des.encrypt(str3);//最后加密
//			return key;
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return null;
//	}
	
}
